package com.plat.net.http.handler;

import com.plat.net.http.context.ControllerContext;
import com.plat.net.http.util.ParamUtil;
import com.plat.net.http.util.ResponseUtil;
import com.plat.net.http.vo.HandleMappingVo;
import com.plat.net.http.vo.HttpRequestVo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.Map;

public class HttpHandler extends SimpleChannelInboundHandler<HttpRequestVo> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpRequestVo requestVo) throws Exception {
        FullHttpRequest request = requestVo.getRequest();
        String uri = ParamUtil.getUri(request);
        HandleMappingVo mappingVo = ControllerContext.getInstance().getHandleMapping(uri);
        //没有对应映射关系，则返回400
        if(mappingVo == null){
            ResponseUtil.sendHttpResponse(ctx, request, ResponseUtil.get400Response());
            return;
        }

        Map<String, String> params = ParamUtil.getRequestParams(request);
        //执行Controller中的方法
        try {
            String content = (String) mappingVo.getMethod().invoke(mappingVo.getInstance(), request, params);
            ResponseUtil.sendHttpResponse(ctx, request, ResponseUtil.get200Response(content));
        }catch (Exception e){
            e.printStackTrace();
            ResponseUtil.sendHttpResponse(ctx, request, ResponseUtil.get500Response());
        }
    }

}